import { Form, Input, Select, Radio, Space, Button, Flex, Divider, Table } from 'antd'
import { useState } from 'react'
import { forwardRef, useImperativeHandle } from 'react'
import styled from 'styled-components'

const BackEndServiceForm = forwardRef(({ style }, ref) => {
  const [form] = Form.useForm()
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  useImperativeHandle(ref, () => ({
    validateFields: form.validateFields,
    getFieldsValue: form.getFieldsValue,
    setFieldsValue: form.setFieldsValue,
  }))

  /* 表格列数据 */
  const columns = [
    {
      title: '参数名称',
      dataIndex: 'name',
      render: (text, record, index) => {
        return (
          <Form.Item name={['serviceParams', index, 'name']} rules={[{ required: true, message: '请填写参数名称' }]}>
            <Input placeholder="请填写参数名称" />
          </Form.Item>
        )
      },
    },
    {
      title: '参数位置',
      dataIndex: 'location',
      render: (text, record, index) => {
        return (
          <Form.Item name={['serviceParams', index, 'location']}>
            <Select
              placeholder="请选择参数位置"
              options={[
                { label: 'PATH', value: 0 },
                { label: 'HEADER', value: 1 },
                { label: 'QUERY', value: 2 },
              ]}
            ></Select>
          </Form.Item>
        )
      },
    },
    {
      title: '必填',
      dataIndex: 'necessary',
      render: (text, record, index) => {
        return (
          <Form.Item name={['serviceParams', index, 'necessary']}>
            <Radio.Group
              options={[
                { label: '是', value: true },
                { label: '否', value: false },
              ]}
            ></Radio.Group>
          </Form.Item>
        )
      },
    },
    {
      title: '默认值',
      dataIndex: 'defaultValue',
      render: (text, record, index) => {
        return (
          <Form.Item name={['serviceParams', index, 'defaultValue']}>
            <Input placeholder="请填写默认值" />
          </Form.Item>
        )
      },
    },
    {
      title: '映射',
      dataIndex: 'mapping',
      render: (text, record, index) => {
        return (
          <Form.Item name={['serviceParams', index, 'mapping']}>
            <Radio.Group
              options={[
                { label: '是', value: true },
                { label: '否', value: false },
              ]}
            ></Radio.Group>
          </Form.Item>
        )
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          <a onClick={() => tableDelete(record.id)}>删除</a>
        </>
      ),
    },
  ]

  const methodOptions = [
    { label: 'GET', value: 'GET' },
    { label: 'POST', value: 'POST' },
    { label: 'DELETE', value: 'DELETE' },
    { label: 'PUT', value: 'PUT' },
    { label: 'PATCH', value: 'PATCH' },
    { label: 'HEAD', value: 'HEAD' },
    { label: 'OPTIONS', value: 'OPTIONS' },
    { label: 'ANY', value: 'ANY' },
  ]
  /* 表格新增 */
  const tableAdd = () => {
    let data = form.getFieldValue('serviceParams') || []
    const newItem = { id: new Date().getTime(), name: '', location: '', mapping: '', defaultValue: '', necessary: '' }
    form.setFieldValue('serviceParams', [...data, newItem])
  }
  /* 表格删除 */
  const tableDelete = (id) => {
    let data = form.getFieldValue('serviceParams') || []
    const newData = data.filter((item) => item.id !== id)
    form.setFieldValue('serviceParams', newData)
  }

  /* 批量删除操作 */
  const handleDelete = () => {
    const data = form.getFieldValue('serviceParams') || []
    const newData = data.filter((item) => !selectedRowKeys.includes(item.id))
    form.setFieldValue('serviceParams', newData)
    setSelectedRowKeys([])
  }

  const onSelectChange = (selectedRowKeys) => {
    setSelectedRowKeys(selectedRowKeys)
  }

  return (
    <Form style={style} layout="horizontal" form={form}>
      <Form.Item name="serviceProtocol" label="协议" rules={[{ required: true, message: '请选择协议' }]}>
        <Select
          placeholder="请选择协议"
          options={[
            { label: 'HTTP', value: 0 },
            { label: 'HTTPS', value: 1 },
          ]}
        ></Select>
      </Form.Item>
      {/* <Form.Item name="appName1" label="代理模式">
                <Radio.Group
                    options={[
                        { label: 'OpenAPI', value: '1' },
                        { label: '反向代理', value: '2' },
                    ]}
                    optionType="button"
                    buttonStyle="solid"
                />
            </Form.Item> */}
      {/* <Form.Item name="method" label="请求方式">
                <Select placeholder="请选请求方式" options={methodOptions}></Select>
            </Form.Item> */}
      <Form.Item name="serviceAddress" label="后端服务地址" rules={[{ required: true, message: '请填写主机名和端口号' }]}>
        <Input placeholder="请填写后端服务地址" />
      </Form.Item>
      {/* <Form.Item name="appName4" label="后端请求Path">
                <Input placeholder="请填写后端请求Path" />
            </Form.Item> */}
      <Form.Item name="overTime" label="后端超时（ms）">
        <Input placeholder="请填写后端超时（ms）" />
      </Form.Item>
      <Divider />
      <StyleWrapper className="table-wrapper">
        <Flex className="table-header" justify={'space-between'} align={'center'}>
          <span className="title">后端服务参数</span>
          <Space>
            <Button type="primary" onClick={tableAdd}>
              添加
            </Button>
            <Button disabled={selectedRowKeys.length ? false : true} danger onClick={handleDelete}>
              批量删除
            </Button>
          </Space>
        </Flex>
        {/* <Form.Item name={'serviceParams'} valuePropName="dataSource">
                    <Table rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }} rowKey="id" size="small" columns={columns} pagination={false} bordered />
                </Form.Item> */}
      </StyleWrapper>
    </Form>
  )
})

const StyleWrapper = styled.div`
  .table-header {
    margin-bottom: 20px;
    .title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .ant-table .ant-form-item {
    margin-bottom: 0;
  }
  .ant-table .ant-table-tbody .ant-table-cell {
    padding: 0;
  }

  .ant-table .ant-form-item-additional {
    position: absolute;
  }
`

export default BackEndServiceForm
